const express = require('express');
const { body, param, query, validationResult } = require('express-validator');
const Department = require('../models/Department');

const router = express.Router();

// 验证错误处理中间件
const handleValidationErrors = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: errors.array()
    });
  }
  next();
};

// 获取部门列表
router.get('/', [
  query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
  query('search').optional().isString().withMessage('搜索关键词必须是字符串'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '' } = req.query;
    const result = await Department.findAll(page, limit, search);
    
    res.json({
      success: true,
      message: '获取部门列表成功',
      data: result
    });
  } catch (error) {
    console.error('获取部门列表错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取部门列表失败'
    });
  }
});

// 获取部门树结构
router.get('/tree', async (req, res) => {
  try {
    const tree = await Department.getDepartmentTree();
    
    res.json({
      success: true,
      message: '获取部门树成功',
      data: tree
    });
  } catch (error) {
    console.error('获取部门树错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取部门树失败'
    });
  }
});

// 获取单个部门
router.get('/:id', [
  param('id').isInt({ min: 1 }).withMessage('部门ID必须是正整数'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { id } = req.params;
    const department = await Department.findById(id);
    
    if (!department) {
      return res.status(404).json({
        success: false,
        message: '部门不存在'
      });
    }
    
    res.json({
      success: true,
      message: '获取部门信息成功',
      data: department
    });
  } catch (error) {
    console.error('获取部门错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取部门失败'
    });
  }
});

// 获取部门下的用户
router.get('/:id/users', [
  param('id').isInt({ min: 1 }).withMessage('部门ID必须是正整数'),
  query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { id } = req.params;
    const { page = 1, limit = 10 } = req.query;
    
    const result = await Department.getUsersByDepartment(id, page, limit);
    
    res.json({
      success: true,
      message: '获取部门用户成功',
      data: result
    });
  } catch (error) {
    console.error('获取部门用户错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取部门用户失败'
    });
  }
});

// 创建部门
router.post('/', [
  body('name').isLength({ min: 2, max: 50 }).withMessage('部门名称长度必须在2-50个字符之间'),
  body('code').isLength({ min: 2, max: 50 }).withMessage('部门代码长度必须在2-50个字符之间'),
  body('parent_id').optional().isInt({ min: 1 }).withMessage('父部门ID必须是正整数'),
  body('leader').optional().isLength({ max: 50 }).withMessage('负责人姓名长度不能超过50个字符'),
  body('description').optional().isLength({ max: 200 }).withMessage('描述长度不能超过200个字符'),
  handleValidationErrors
], async (req, res) => {
  try {
    const departmentData = req.body;
    
    const newDepartment = await Department.create(departmentData);
    
    res.status(201).json({
      success: true,
      message: '创建部门成功',
      data: newDepartment
    });
  } catch (error) {
    console.error('创建部门错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '创建部门失败'
    });
  }
});

// 更新部门
router.put('/:id', [
  param('id').isInt({ min: 1 }).withMessage('部门ID必须是正整数'),
  body('name').optional().isLength({ min: 2, max: 50 }).withMessage('部门名称长度必须在2-50个字符之间'),
  body('code').optional().isLength({ min: 2, max: 50 }).withMessage('部门代码长度必须在2-50个字符之间'),
  body('parent_id').optional().isInt({ min: 1 }).withMessage('父部门ID必须是正整数'),
  body('leader').optional().isLength({ max: 50 }).withMessage('负责人姓名长度不能超过50个字符'),
  body('description').optional().isLength({ max: 200 }).withMessage('描述长度不能超过200个字符'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { id } = req.params;
    const departmentData = req.body;
    
    const updatedDepartment = await Department.update(id, departmentData);
    
    res.json({
      success: true,
      message: '更新部门成功',
      data: updatedDepartment
    });
  } catch (error) {
    console.error('更新部门错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '更新部门失败'
    });
  }
});

// 删除部门
router.delete('/:id', [
  param('id').isInt({ min: 1 }).withMessage('部门ID必须是正整数'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { id } = req.params;
    
    await Department.delete(id);
    
    res.json({
      success: true,
      message: '删除部门成功'
    });
  } catch (error) {
    console.error('删除部门错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '删除部门失败'
    });
  }
});

// 批量删除部门
router.delete('/', [
  body('ids').isArray({ min: 1 }).withMessage('必须提供要删除的部门ID数组'),
  body('ids.*').isInt({ min: 1 }).withMessage('部门ID必须是正整数'),
  handleValidationErrors
], async (req, res) => {
  try {
    const { ids } = req.body;
    
    const deletedCount = await Department.deleteMultiple(ids);
    
    res.json({
      success: true,
      message: `成功删除 ${deletedCount} 个部门`,
      data: { deletedCount }
    });
  } catch (error) {
    console.error('批量删除部门错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '批量删除部门失败'
    });
  }
});

// 获取部门统计信息
router.get('/stats/overview', async (req, res) => {
  try {
    const stats = await Department.getStats();
    
    res.json({
      success: true,
      message: '获取部门统计成功',
      data: stats
    });
  } catch (error) {
    console.error('获取部门统计错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取部门统计失败'
    });
  }
});

// 获取所有部门（用于下拉选择）
router.get('/options/all', async (req, res) => {
  try {
    const departments = await Department.getAllDepartments();
    
    res.json({
      success: true,
      message: '获取部门选项成功',
      data: departments
    });
  } catch (error) {
    console.error('获取部门选项错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取部门选项失败'
    });
  }
});

module.exports = router; 